from datetime import datetime
from fastapi import APIRouter, Query, Depends

from core.dependencies import get_redis_service, get_sender_tools
from core.logger import log
from db.models.chat_message import ChatMessageModel, UpdateConversationRequest, DeleteConversationRequest
from db.models.wx_friends import  MessageParams
from services.wx_chat_messages import get_chat_counts, get_history_chat_by_time_range, \
    delete_wx_message, chat_set_lock, chat_unlock, create_chat_mode, get_chat_mode, delete_chat_mode, send_message, \
    generate_des_and_set_remark

from utils.rag_api import  add_qa
from utils.result import Result
from utils.sender_tools import SenderTools

router = APIRouter()


@router.get("/chat_counts")
async def chat_counts():
    return await get_chat_counts()
@router.post("/message/description")
async def get_wyy_status(data: dict[str,str]):
    """生成聊天摘要"""
    return await generate_des_and_set_remark(data["wx_id"], data["device_id"])
@router.get("/message/history")
async def wx_message(wx_id: str = Query(...),
                     device_id: str = Query(...),
                     start_time: datetime = Query(...),
                     end_time: datetime = Query(...)):
    return await get_history_chat_by_time_range(wx_id, device_id,start_time,end_time)
@router.post("/wx_message/send")
async def wx_message(req: MessageParams,sender:SenderTools=Depends(get_sender_tools)):
    return await send_message(req,sender)

@router.post("/conversation/update")
async def update_conversation(req: UpdateConversationRequest):
    if await add_qa(req.questions,req.answers,req.template_name):
        return Result.success(msg="更新成功")
    return Result.fail(msg="更新失败")

@router.post("/conversation/delete")
async def delete_conversation(req: DeleteConversationRequest):
    log.info(f"删除会话,删除人的微信id：{req.wx_id}")
    return await delete_wx_message(req.device_id,req.wx_id)

@router.post("/conversation/mode")
async def chat_mode(template_name:str,redis_service=Depends(get_redis_service)):
    return await create_chat_mode(template_name,redis_service)
@router.get("/conversation/mode")
async def chat_mode(redis_service=Depends(get_redis_service)):
    return await get_chat_mode(redis_service)

@router.delete("/conversation/mode")
async def chat_mode(template_name:str,redis_service=Depends(get_redis_service)):
    return await delete_chat_mode(template_name=template_name,redis_service=redis_service)
@router.post("/test/seeee")
async def test_see(data:dict[str,str]):
    return ChatMessageModel.generate_session_id(data["sender_id"], data["receiver_id"])


@router.post("/chat/lock")
async def chat_lock(req: DeleteConversationRequest):
    return await chat_set_lock(req.device_id, req.wx_id)

@router.post("/chat/unlock")
async def chat_lock(req: DeleteConversationRequest):
    return await chat_unlock(req.device_id, req.wx_id)
